<?php
	// Usage:
	// php makewebsite.php <source directory> [<destination directory>]
	// Source directory: should contain the folders with movies
	// Destination directory: the directory in which the "website" should be created. If not given, current working directory.
	//                        this directory will be created if required.
	
	$folder = opendir($argv[1]);
	umask(0);
	if(isset($argv[2])){
		$webbasedir = $argv[2];
	}else{
		$webbasedir = getcwd()."/";
	}
	
	if(!file_exists($webbasedir)){
		mkdir($webbasedir,0777,1);
	}

	if(!file_exists($webbasedir."data/")){
		mkdir($webbasedir."data");
	}
	if(!file_exists($webbasedir."data/movies/")){
		mkdir($webbasedir."data/movies");
	}
	if(!file_exists($webbasedir."data/covers/")){
		mkdir($webbasedir."data/covers");
	}
	if(!file_exists($webbasedir."data/files/")){
		mkdir($webbasedir."data/files");
	}
	
	$temp = explode("/",$argv[1]);
	$basedirname = $temp[count($temp)-2];
	
	$allmovies = array();
	$allmoviesdata = array();
	
	$allgenres	= array();
	$allyears	= array();
	$allrates	= array();
	
	$allsubs = array();
	$allcovers = array();
	
	while(false !== ($file = readdir($folder))){
		if(substr($file, 0, 1) == "."){ continue; }
		$tmp = scandir($argv[1]."/".$file);

		$imdbnr = md5($file);
		$ffile = fopen($webbasedir."data/files/".$imdbnr.".xml","w");
		fwrite($ffile, "<files>\n");
		foreach($tmp as $df){
			if(substr($df,0,1) == "."){ continue; }
			fwrite($ffile, "\t<file><![CDATA[".$df."]]></file>\n");
		}
		fwrite($ffile, "</files>\n");

		
		
		
		foreach($tmp as $df){
			if(substr($df,0,1) == "."){ continue; }
			if(strpos($df, "trailer") > 1){ continue; } // Ignore trailers... - problem: will also ignore movies with "trailer" in name :(
			if(strpos($df, "sample") > 1){ continue; } // Same for sample files
			if(strpos($df, "xml") > 1){
				$dom = new DomDocument();
				$dom->load($argv[1]."/".$file."/".$df);
				$temp = xml2array($dom);
				
//				$imdbnr = trim(implode("",file($argv[1]."/".$file."/imdbnr.txt")));
				$imdbnr = md5($file);
				if(file_exists($argv[1]."/".$file."/".str_replace(".xml",".srt",$df))){
					array_push($allsubs, $imdbnr);
				}
				if(file_exists($argv[1]."/".$file."/cover.jpg")){
					makecover($argv[1]."/".$file."/cover.jpg",$imdbnr);
					array_push($allcovers, $imdbnr);
				}
				makemoviepage($imdbnr,$temp);
				copy($argv[1]."/".$file."/".$df, $webbasedir."data/movies/".$imdbnr.".xml");

				continue(2);
			}
		}
	}
	makeindexpage();
	
function makeindexpage(){
	global $webbasedir, $allmovies, $allsubs, $allcovers, $allmoviesdata;
	$htm = fopen($webbasedir."data/movies.xml","w");
	
	$titles = array_keys($allmovies);
	sort($titles);
	fwrite($htm, '<movies>'."\n");
	foreach($titles as $title){
		if($title != ""){
			$imdbnr = $allmovies[$title];
			$genres = array();
			if(is_array($allmoviesdata[$imdbnr]["genres"])){
				foreach($allmoviesdata[$imdbnr]["genres"] as $genre){
					if(substr($genre["cdata"],0,4) != "IMDb"){
						array_push($genres, $genre["cdata"]);
					}
				}
			}
			fwrite($htm, '	<movie id="'.$allmovies[$title].'" year="'.$allmoviesdata[$imdbnr]["year"].'" genres="'.implode(",",$genres).'" rating="'.$allmoviesdata[$imdbnr]["rating"].'" subtitles="'.(in_array($allmovies[$title],$allsubs)?'1':'0').'" cover="'.(in_array($allmovies[$title],$allcovers)?'1':'0').'"><![CDATA['.$title.']]></movie>'."\n");
		}
	}
	fwrite($htm,'</movies>');
}








function makecover($source, $imdbnr){
	global $webbasedir;
	
	copy($source, $webbasedir."data/covers/".$imdbnr.".jpg");
	exec("sips -Z 350 '".$webbasedir."data/covers/".$imdbnr.".jpg'");
/*
	-- code below doesn't seem to work on OS X (no GD lib in the build-in PHP)
	$im = imagecreatefromjpeg($source);
	$mw = 350;
	$mh = 150;
	$w = imagesx($im);
	$h = imagesy($im);
	$scale = min($mw/$w, $mh/$h);
	$dest = imagecreatetruecolor($w*$scale,$h*$scale);
	imagecopyresized($dest, $im, 0, 0, 0, 0, $w*$scale, $h*$scale, $w, $h);
	imagejpeg($dest,$webbasedir."movies/covers/".$imdbnr.".jpg");
*/
}
	
function makemoviepage($imdbnr,$moviearray){
	global $webbasedir, $allmovies, $allgenres, $allrates, $allyears, $allmoviesdata;
	$moviearray["media"][0]["title"][0]["cdata"] = preg_replace("/\/.*/","",$moviearray["media"][0]["title"][0]["cdata"]);
	
	$allmovies[$moviearray["media"][0]["title"][0]["cdata"]] = $imdbnr;
	$allmoviesdata[$imdbnr] = array("rating"=>$moviearray["media"][0]["imdbRating"][0]["cdata"], "genres"=>$moviearray["media"][0]["genres"][0]["genre"], "year"=>substr($moviearray["media"][0]["published"][0]["cdata"],0,4));
}

function xml2array($domnode)
{
	$nodearray = array();
	$domnode = $domnode->firstChild;
	while (!is_null($domnode))
	{
		$currentnode = $domnode->nodeName;
		switch ($domnode->nodeType)
		{
			case XML_TEXT_NODE:
				if(!(trim($domnode->nodeValue) == "")) $nodearray['cdata'] = $domnode->nodeValue;
				break;
			case XML_ELEMENT_NODE:
				if ($domnode->hasAttributes() )
				{
					$elementarray = array();
					$attributes = $domnode->attributes;
					foreach ($attributes as $index => $domobj)
					{
						$elementarray[$domobj->name] = $domobj->value;
					}
				}
				break;
			case 4:
				if(!(trim($domnode->nodeValue) == "")) $nodearray['cdata'] = $domnode->nodeValue;
				break;
		}
		if ( $domnode->hasChildNodes() )
		{
			$nodearray[$currentnode][] = xml2array($domnode);
			if (isset($elementarray))
			{
				$currnodeindex = count($nodearray[$currentnode]) - 1;
				$nodearray[$currentnode][$currnodeindex]['@'] = $elementarray;
			}
		} else {
			if (isset($elementarray) && $domnode->nodeType != XML_TEXT_NODE)
			{
				$nodearray[$currentnode]['@'] = $elementarray;
			}
		}
		$domnode = $domnode->nextSibling;
	}
	return $nodearray;
}



	exit;
?>